import 'package:star_author/config/api.dart';
import 'package:star_author/config/app.dart';
import 'package:star_author/config/base_configuration.dart';
import 'package:star_author/config/ui_constant.dart';
import 'package:star_author/model/backflow.dart';
import 'package:star_author/model/channel.dart';
import 'package:star_author/project_widgets/custom_willpop_scope.dart';
import 'package:star_author/provider/index.dart';
import 'package:star_author/route/route_util.dart';
import 'package:star_author/utils/clipper.dart';
import 'package:star_author/utils/common_util/date_util.dart';
import 'package:star_author/utils/config_provider_util.dart';
import 'package:star_author/utils/event.dart';
import 'package:star_author/utils/guide_user_util.dart';
import 'package:star_author/utils/rouces_util.dart';
import 'package:star_author/utils/statistics/event/backflow_event.dart';
import 'package:star_author/utils/statistics/huiliu/event.dart';
import 'package:star_author/utils/statistics/huiliu/huiliu_statistics.dart';
import 'package:star_author/utils/statistics/statistics.dart';
import 'package:star_author/utils/string_util.dart';
import 'package:star_author/utils/toast_util.dart';
import 'package:star_author/views/products/bidder_goods_detail_page/bidder_goods_detail_handler.dart';
import 'package:star_author/views/products/bidder_goods_detail_page/widgets/comment_list.dart';
import 'package:star_author/views/products/widgets/detail_preview_widget.dart';
import 'package:star_author/views/products/widgets/error_widget.dart';
import 'package:star_author/views/products/widgets/loading_widget.dart';
import 'package:star_author/views/products/widgets/relate_load_more_list_widget.dart';
import 'package:star_author/views/products/widgets/share_icon_widget.dart';
import 'package:star_author/views/products/widgets/tender_form_dialog.dart';
import 'package:star_author/views/stream/dialog/live_recording_dialog.dart';
import 'package:star_author/widgets/base_widget/app_bar/custom_app_bar.dart';
import 'package:star_author/widgets/button_widget.dart';
import 'package:star_author/widgets/countdown/count_down_view.dart';
import 'package:star_author/widgets/dialog/sure_dialog.dart';
import 'package:star_author/widgets/down_count_widget.dart';
import 'package:star_author/widgets/empty_view/h_empty_view.dart';
import 'package:star_author/widgets/empty_view/v_empty_view.dart';
import 'package:star_author/widgets/push_to_refresh_header.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh_notification/pull_to_refresh_notification.dart';

import '../../../utils/http/http_util.dart';
import '../../../utils/user_util.dart';
import '../../../utils/utils.dart';
import '../../../widgets/constraints_widget.dart';
import '../../../widgets/copy_text.dart';
import '../../../widgets/custom_button/go_back_button.dart';
import '../../../widgets/dialog/dialog_type.dart';
import '../bidding_product_list_item.dart';

double loveWidth = 45;

///买家品详情
class BidderGoodsDetailPage extends StatefulWidget {
  static String routeName = '/BidderGoodsDetailPage';
  final int id;
  final BiddingProductListItemFormType formDetail;
  final int orderId;
  final int kBackflowId;
  final bool isNeedShowPriceDialog; //是否需要出价弹框显示

  BidderGoodsDetailPage({
    Key? key,
    required this.id,
    this.formDetail = BiddingProductListItemFormType.BiddingDetail,
    this.orderId = -1,
    this.kBackflowId = -1,
    this.isNeedShowPriceDialog: false,
  }) : super(key: key);

  _BidderGoodsDetailPageState createState() => _BidderGoodsDetailPageState();
}

class _BidderGoodsDetailPageState extends State<BidderGoodsDetailPage>
    with TickerProviderStateMixin, WidgetsBindingObserver {
  BackflowModel? data;

  List? comments;

  List<String> evaluationStatusList = ['evaluation', 'waitconfirm'];

  List<String> onsaleStatusList = ['onsale', 'sold', 'finished', 'back'];

  List<GlobalKey> guideGlobalKeyList = [GlobalKey()];

  ScrollController scrollController = ScrollController();

  double _opacity = 0.0;

  initProductData({
    bool isInit: false,
    bool isNeedLoading: false,
  }) async {
    if (isNeedLoading) {
      setState(() {
        isLoading = true;
      });
    }
    HttpUtil.commonRequest(
      Get.context!,
      '/api/v1/backflows/${widget.id}',
      isLoading: false,
    ).then((value) {
      Map<String, dynamic> _data = value.data ?? {};
      data = BackflowModel(_data);
      if (isInit) {
        HuiLiuStatistics().event(HuiLiuEvent.view_backflow_detail, {
          'id': data?.id ?? 0,
        });
        StatisticsUtil.event(
            BiddingEvent.into_detail,
            getUMengMap({
              "backflow_id": (data?.id ?? 0).toString(),
            }));
      }
      if (isInit) {
        //如果是直播间进来 需要弹出来输入框
        if ([
          BiddingProductListItemFormType.Live,
          BiddingProductListItemFormType.ItemCard
        ].contains(widget.formDetail)) {
          if (widget.isNeedShowPriceDialog) {
            Future.delayed(Duration(milliseconds: 100), () {
              if (!isMine) {
                TenderFormDialogUtil.show(
                    widget.id,
                    () {
                      initCommentData();
                      initProductData();
                    },
                    data?.originalData ?? {},
                    previous_max_tender_price:
                        data?.previous_max_tender_price ?? 0,
                    price_range: data?.priceRange ?? [],
                    nextCall: () {
                      GuideUserUtil.startShowCase(
                        Get.context!,
                        guideGlobalKeyList,
                        GuideUserUtil.bidder_goods_detaill_page,
                      );
                    });
              }
            });
          }
        }
      }
      isLoading = false;
      isError = false;
      updateState();
    }).catchError((e) {
      isError = true;
      updateState();
    });
  }

  bool isError = false;

  //是否加载中
  bool isLoading = true;

  void updateState() {
    if (mounted) {
      setState(() {});
    }
  }

  void initCommentData() async {
    HttpUtil.commonRequest(
      Get.context!,
      '/api/v1/tenders',
      queryParameters: {'backflow_id': widget.id},
      isLoading: false,
      isErrorToast: false,
    ).then(
      (value) {
        List _comment = value.data['data'] ?? [];
        comments = _comment;
        if (![
          BiddingProductListItemFormType.Live,
          BiddingProductListItemFormType.ItemCard
        ].contains(widget.formDetail)) {
          GuideUserUtil.startShowCase(
            Get.context!,
            guideGlobalKeyList,
            GuideUserUtil.bidder_goods_detaill_page,
          );
        }
        updateState();
      },
    );
  }

  @override
  void initState() {
    super.initState();
    scrollController.addListener(() {
      double max = 100;
      double a = scrollController.offset / 100;
      if (scrollController.offset <= 0) {
        _opacity = 0;
        updateState();
      } else if (scrollController.offset >= max) {
        _opacity = 1;
        updateState();
      } else {
        _opacity = a;
        updateState();
      }
    });
    WidgetsBinding.instance?.addObserver(this); // 注册监听器
    addEvent();
    _left = Get.width - width.w - 20.w - 20.w;
    WidgetsBinding.instance?.addPostFrameCallback((timeStamp) {
      initProductData(
        isInit: true,
        isNeedLoading: true,
      );
      initCommentData();
      initTips();
    });
  }

  String title = "";
  String body = "";

  initTips() {
    HttpUtil.commonRequest(
      Get.context!,
      '/api/v1/tender_tips/',
      isLoading: false,
      isCatchErrorLogin: false,
    ).then((value) {
      title = value.data['title'] ?? "竞拍小提示";
      body = value.data['body'] ?? "";
      if (mounted) setState(() {});
    });
  }

  addEvent() {
    Event.on("refresh", (arg) {
      initProductData();
      initCommentData();
    });
  }

  offEvent() {
    Event.off('refresh');
  }

  String appBarTitle = "${App.evaluation_text}详情";

  GlobalKey videoKey = GlobalKey();

  double _left = 20;
  double _top = 200;

  @override
  void dispose() {
    super.dispose();
    scrollController.dispose();
    WidgetsBinding.instance?.removeObserver(this); // 注册监听器
    offEvent();
  }

  UserProvider get model {
    return Provider.of<UserProvider>(
      Get.context!,
      listen: false,
    );
  }

  int currentIndex = 0;

  buildDownloadWidget(images, videos) {
    return GestureDetector(
      child: RoucesUtil.getAssetsIcon('common/download', 30.w),
      onTap: () {
        BidderGoodsDetailHandler.downloadFile(
            currentIndex, images[currentIndex], videos);
      },
      behavior: HitTestBehavior.opaque,
    );
  }

  buildDetailPreviewWidget() {
    String shareIconWidget = '';
    if (data?.goods["cover"] != null &&
        data?.goods["cover"].isNotEmpty &&
        data?.goods["cover"]["url"] != null) {
      shareIconWidget = data?.goods["cover"]["url"] ?? "";
    }
    List images = data?.images ?? [];
    List videos = data?.videos ?? [];
    if (images.length == 0 && videos.length == 0) {
      return ConstraintsWidget(width: '100vw', height: '100vw');
    }
    return Container(
      child: Stack(
        children: [
          DetailPreviewWidget(
            images: data?.images ?? [],
            videos: data?.videos ?? [],
            sonance: data?.sonance ?? false,
            status: data?.status ?? "",
            studios: data?.studios ?? [],
            indexChanged: (int index) {
              currentIndex = index;
            },
          ),
          Positioned(
            child: GestureDetector(
              child: RoucesUtil.getAssetsIcon('ic_good_detail_back_lt', 30.w),
              onTap: () async {
                Get.back();
              },
            ),
            left: 12.w,
            top: 12.w,
          ),
          Container(
              width: Get.width,
              height: 40.w,
              margin: EdgeInsets.only(
                top: 12.w,
                right: 12.w,
                left: 12.w,
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  buildDownloadWidget(images, videos),
                  SizedBox(
                    width: 10.w,
                  ),
                  ShareIconWidget(
                    image: shareIconWidget,
                    title: data?.goods["title"] ?? "回流",
                    id: data?.id ?? 0,
                    shareType: 1,
                    backflowModal: data,
                  ),
                ],
              )),
        ],
      ),
    );
  }

  PreferredSizeWidget buildPreferredSizeWidget(shareIconWidget) {
    return CustomAppBar(
      Text(appBarTitle),
      actions: [
        ShareIconWidget(
          image: shareIconWidget,
          title: data?.goods["title"] ?? "回流",
          id: data?.id ?? 0,
          shareType: 1,
          backflowModal: data,
          icon: "ic_share_lt",
        ),
      ],
      automaticallyImplyLeading: false,
      leading: GoBackButton(
        color: Colors.black,
        callback: () {
          if (widget.isNeedShowPriceDialog) {
            Get.back(result: data?.tenderPrice ?? "");
          } else {
            Get.back();
          }
        },
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    String? _status = data?.status;
    String shareIconWidget = '';
    if (data?.goods["cover"] != null &&
        data?.goods["cover"].isNotEmpty &&
        data?.goods["cover"]["url"] != null) {
      shareIconWidget = data?.goods["cover"]["url"] ?? "";
    }
    return CustomWillPopScope(
      child: SafeArea(
        child: Container(
          color: Colors.white,
          child: Stack(
            children: [
              PullToRefreshNotification(
                child: CustomScrollView(
                  controller: scrollController,
                  slivers: [
                    SliverToBoxAdapter(
                      child: PullToRefreshHeader(),
                    ),
                    SliverToBoxAdapter(
                      child: Column(
                        children: [
                          if (isMine)
                            Container(
                              color: ColorConf.red,
                              height: 30.w,
                              child: Center(
                                child: Text(
                                  '我的货品',
                                  style: TextStyle(
                                    fontSize: 14.sp,
                                    color: ColorConf.white,
                                  ),
                                ),
                              ),
                            ),
                          buildDetailPreviewWidget(),
                          render(),
                          Container(
                            height: 10.w,
                            color: Color(0xFFF5F5F5),
                            width: double.infinity,
                          ),
                          MyComment(
                            data: data,
                          ),
                          BidDescription(),
                        ],
                      ),
                    ),
                    if (model.isBidder) ...[
                      RelateListTitleWidget(title: '相关货品'),
                      RelateLoadMoreListWidget(
                        queryParameters: {
                          'ids': widget.id,
                          'status': _getStatus(_status),
                        },
                        detail: widget.formDetail,
                        color: Colors.white,
                      ),
                      SliverToBoxAdapter(
                        child: VEmptyView(
                            52.w + MediaQuery.of(context).padding.bottom),
                      ),
                    ]
                  ],
                ),
                onRefresh: () async {
                  initProductData();
                  return true;
                },
              ),
              Positioned(
                left: 0,
                right: 0,
                bottom: 0,
                child: Column(
                  children: [
                    //显示播放讲解回复
                    buildLiveRecordingWidget(),
                    renderFooter(data)
                  ],
                ),
              ),
              if (isLoading) LoadingWidget(),
              if (isError)
                CustomErrorWidget(
                  click: () {
                    initProductData(
                      isInit: true,
                      isNeedLoading: true,
                    );
                    initCommentData();
                  },
                ),
              if (_opacity > 0)
                Positioned(
                    child: AnimatedOpacity(
                  child: Container(
                    child: buildPreferredSizeWidget(shareIconWidget),
                    height: MediaQuery.of(context).padding.top,
                    color: Colors.white,
                  ),
                  opacity: _opacity,
                  duration: Duration(milliseconds: 500),
                )),
            ],
          ),
        ),
        bottom: false,
      ),
      onWillPop: true,
      action: () {
        //需要弹框 表示是从卡片点击出价的 需要返回价格
        //如果有出价就需要刷新页面
        if (widget.isNeedShowPriceDialog) {
          Get.back(result: data?.tenderPrice ?? "0");
        } else {
          Get.back();
        }
      },
    );
  }

  buildLiveRecordingWidget() {
    bool has_video = (data?.recording_video.isNotEmpty ?? false);
    if (['evaluation'].contains(data?.status)) {
      String text = "观看讲解回放，出价更有把握";
      String buttonText = "立即观看";
      //都没有值直接空
      if (data?.priceRange.length == 0 && !has_video) {
        return Container();
      } else {
        if (data?.priceRange.length != 0) {
          text = "源头市场价 " +
              getPriceWithList(
                data?.priceRange ?? [],
                show_name: data?.originalData['price_range_show_name'] ?? "",
                intl: true,
              );
        }
        buttonText = "观看讲解回放";
      }

      return GestureDetector(
        child: Container(
          height: 40.w,
          color: Color(0xCCFF7B47),
          width: Get.width,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              if (has_video)
                RoucesUtil.getAssetsIcon('ic_bidder_detail_play_lt', 16),
              Container(
                margin: EdgeInsets.only(left: 6.w),
                child: Text(
                  text,
                  style: TextStyle(
                    fontSize: 14.sp,
                    color: Colors.white,
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ),
              if (has_video)
                Container(
                  height: 20.w,
                  margin: EdgeInsets.only(left: 10.w),
                  alignment: Alignment.center,
                  padding: EdgeInsets.symmetric(
                    horizontal: 6,
                  ),
                  decoration: BoxDecoration(
                      color: Colors.transparent,
                      borderRadius: BorderRadius.circular(4),
                      border: Border.all(width: 1, color: Colors.white)),
                  child: Text(
                    buttonText,
                    style: TextStyle(
                      fontSize: 12.sp,
                      color: Colors.white,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                )
            ],
          ),
        ),
        behavior: HitTestBehavior.opaque,
        onTap: () {
          Map<String, dynamic>? map = data?.toJson(data!);
          LiveRecordingDialogUtil.showDialog(
            data?.recording_video ?? "",
            StreamConf.liveId,
            {
              ...map!,
              "is_living":
                  widget.formDetail == BiddingProductListItemFormType.Live,
            },
            liveRecordForm: LiveRecordForm.DetailNoLiving,
          );
        },
      );
    }
    return Container();
  }

  double width = 58;
  double height = 62;

  Widget buildStreamView() {
    return Listener(
      child: GestureDetector(
        child: Container(
          width: width.w,
          height: height.w,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Container(
                child: Image.asset(
                  'images/video_loading_lt.gif',
                  width: 13.w,
                  height: 13.w,
                  color: Color(0xFFF86138),
                ),
                alignment: Alignment.center,
                width: 22.w,
                height: 22.w,
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(50),
                ),
              ),
              SizedBox(
                height: 2.w,
              ),
              Text(
                "直播看货",
                style: TextStyle(
                    fontSize: 12.sp,
                    color: Colors.white,
                    fontWeight: FontWeight.w500),
              )
            ],
          ),
          decoration: BoxDecoration(
            color: Color(0xCCFF7B47),
            borderRadius: BorderRadius.circular(8.w),
          ),
        ),
        //拖拽更新
        onPanUpdate: (details) {
          var pixelDetails = MediaQuery.of(context).size; //获取屏幕信息
          //拖拽后更新按钮信息，是否处于边缘
          double x = _left + details.delta.dx;
          double y = _top + details.delta.dx;
          double maxHeight = pixelDetails.height - height.w - 55.w - 110.w;
          if (y >= 0 && y <= maxHeight) {
            _top += details.delta.dy;
          } else if (y <= 0) {
            _top = 0;
          } else if (y >= maxHeight) {
            _top = maxHeight;
          }
          if (x >= 0 && x <= pixelDetails.width - width.w) {
            _left += details.delta.dx;
          } else if (x <= 0) {
            //左边边缘
            _left = 0;
          } else if (x >= pixelDetails.width - width.w) {
            //右边边缘
            _left = Get.width - width.w - 20.w;
          }
          updateState();
        },
        onTap: () {},
      ),
    );
  }

  Widget? renderTenderBannerLeft(BackflowModel? data) {
    if (data == null) {
      return Container();
    }
    String status = data.status;
    if (status == 'evaluation') {
      int already_tenders_count = data.tendersCount;
      return Container(
        padding: GetPadding.only(left: 21.w),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              '竞拍中',
              style: TextStyle(
                fontWeight: FontWeight.w600,
                color: ColorConf.white,
                fontSize: 14.sp,
              ),
            ),
            SizedBox(
              height: 3.w,
            ),
            Text(
              '已有 $already_tenders_count 人出价${data.isConditionStopTime ? "，即将提前结拍" : ""}',
              style: TextStyle(
                fontSize: 12.sp,
                color: ColorConf.white,
              ),
            )
          ],
        ),
      );
    } else {
      String? immediateDiscountPrice = data.immediate_discount_price;
      return Container(
        padding: GetPadding.only(left: 21.w, right: 24.w),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            RichText(
                text: TextSpan(children: [
              TextSpan(text: '回款价 ', style: TextStyle(fontSize: 12.sp)),
              TextSpan(
                text: '￥',
                style: TextStyle(
                  fontSize: 12.sp,
                  fontWeight: FontWeight.bold,
                ),
              ),
              TextSpan(
                text: immediateDiscountPrice,
                style: TextStyle(
                  fontSize: 24.sp,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ]))
          ],
        ),
      );
    }
  }

  Widget buildFinishAuctionWidget({String title: "结拍倒计时", Function? click}) {
    return GestureDetector(
      child: Row(
        children: [
          getDefaultText(
            title,
            UIConstant.color33,
            fontWeight: FontWeight.w400,
          ),
          SizedBox(
            width: 2.w,
          ),
          Image.asset(
            "images/ic_order_doubt_lt.png",
            width: 12.w,
            height: 12.w,
          ),
          SizedBox(
            width: 6.w,
          ),
        ],
        mainAxisAlignment: MainAxisAlignment.center,
      ),
      behavior: HitTestBehavior.opaque,
      onTap: () {
        if (click != null) {
          click();
        } else {
          DialogUtil.showMyDialog(
              dialogType: DialogType.conclusion_countdown,
              param: {
                "expired_evaluation_duration":
                    data?.expired_evaluation_duration ?? 48,
              });
        }
      },
    );
  }

  Widget getDefaultText(String text, Color color,
      {double? fontSize, FontWeight fontWeight: FontWeight.w600}) {
    return Container(
      padding: GetPadding.only(left: 10.w),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Text(
            text,
            style: TextStyle(
              fontWeight: fontWeight,
              color: color,
              fontSize: fontSize ?? 14.sp,
            ),
          ),
        ],
      ),
    );
  }

  successOnTap() {
    DialogUtil.showMyDialog(
        dialogType: DialogType.returnMoneyToBack,
        money: data?.immediate_discount_price ?? "0",
        compensate: (data?.compensate ?? "").toString(),
        leftButtonOnTap: () {},
        rightButtonOnTap: () async {
          EasyLoading.show(status: "请稍等...");
          await API.confirmImmediate(data?.id);
          EasyLoading.dismiss();
          Event.emit('refresh');
        });
  }

  Widget? renderTenderBannerRight(BackflowModel? data) {
    if (data == null) {
      return Container();
    }
    String? status = data.status;

    Widget renderTimeContainer(String text) {
      return Container(
        padding: EdgeInsets.symmetric(vertical: 4.w),
        width: 22.w,
        decoration: BoxDecoration(
          borderRadius: GetRadius.all(3.w),
          color: ColorConf.orange,
        ),
        child: Text(
          text,
          textAlign: TextAlign.center,
          style: TextStyle(
            color: ColorConf.white,
            fontSize: 12.sp,
          ),
        ),
      );
    }

    Widget renderDivider(String text) {
      return Container(
        padding: GetPadding.only(left: 4.w, right: 4.w),
        child: Text(
          text,
          style: TextStyle(
            color: ColorConf.orange,
            fontSize: 12.sp,
          ),
        ),
      );
    }

    Map<String, Widget Function(BackflowModel)> renderMap = {
      'evaluation': (BackflowModel _data) {
        Duration countDownVal = Duration(seconds: 0);
        String endTimeStr = _data.expired_evaluated_at ?? "";
        if (_data.isConditionStopTime) {
          endTimeStr = _data.condition_stop_time;
        }
        if (endTimeStr.isNotEmpty) {
          countDownVal =
              DateUtil.getDateTime(endTimeStr)!.difference(DateTime.now());
        }

        int countDownSecond = countDownVal.inSeconds;

        if (countDownSecond <= 0)
          return Container(
            child: getDefaultText(
                '${App.evaluation_text}出价中...', ColorConf.yellow),
          );

        return CountdownView(
          countDownVal,
          Duration(seconds: 1),
          (context, remaining) {
            String hour = "";
            String minute = "";
            String seconds = "";

            hour = StringUtil.toTwoDigits(remaining.inHours);

            minute = StringUtil.toTwoDigits(remaining.inMinutes.remainder(60));

            seconds = StringUtil.toTwoDigits(remaining.inSeconds.remainder(60));

            return Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                buildFinishAuctionWidget(),
                SizedBox(
                  height: 5.w,
                ),
                Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    renderTimeContainer(hour),
                    renderDivider(':'),
                    renderTimeContainer(minute),
                    renderDivider(':'),
                    renderTimeContainer(seconds),
                  ],
                )
              ],
            );
          },
          Container(),
          onFinish: () {
            initProductData();
          },
          isStartWhenInit: true,
        );
      },
      'waitconfirm': (BackflowModel _data) {
        String expiredAt = _data.expiredAt ?? "";
        return Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Container(
              margin: GetPadding.only(bottom: 4.w),
              child: Text(
                '待卖家确认',
                style: TextStyle(
                  color: UIConstant.color33,
                  fontSize: 14.sp,
                ),
              ),
            ),
            DownCountWidget(end: expiredAt),
          ],
        );
      },
      'wait_pay': (BackflowModel _data) {
        String timeStr =
            _data.winning_order?["expected_deduct_guarantee_at"] ?? "";

        return Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Container(
              margin: GetPadding.only(bottom: 4.w),
              child: Text(
                '待支付中拍款',
                style: TextStyle(
                  color: UIConstant.color33,
                  fontSize: 14.sp,
                ),
              ),
            ),
            DownCountWidget(end: timeStr),
          ],
        );
      },
      'onsale': (BackflowModel _data) {
        return getDefaultText('平台寄售中', ColorConf.yellow);
      },
      'sold': (BackflowModel _data) {
        return getDefaultText('平台寄售中', ColorConf.yellow);
      },
      'finished': (BackflowModel _data) {
        return RichText(
          text: TextSpan(
            style: TextStyle(
              color: ColorConf.normal,
              fontSize: 14.sp,
            ),
            children: [
              TextSpan(
                text: '回流已完成',
                style: TextStyle(color: ColorConf.yellow, fontSize: 14.sp),
              ),
            ],
          ),
        );
      },
      'back': (BackflowModel _data) {
        return getDefaultText('回流已取消', ColorConf.lightGray);
      },
      'closed': (BackflowModel _data) {
        return getDefaultText('回流已取消', ColorConf.lightGray);
      }
    };

    Function? func = renderMap[status];
    return func != null ? func(data) : null;
  }

  bool get isMine {
    return data?.isMine(UserUtil.getUserId(Get.context!)) ?? false;
  }

  Widget buildServiceWidget() {
    return Container(
      alignment: Alignment.center,
      child: GestureDetector(
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            RoucesUtil.getAssetsIcon("user/service", 19.w),
            SizedBox(
              width: 5.w,
            ),
            Text(
              "客服",
              style: TextStyle(color: Color(0xFF333333), fontSize: 10.sp),
            )
          ],
        ),
        onTap: () {},
      ),
    );
  }

  double buttom_height = 52.w + 7.5.w;

  Widget renderFooter(BackflowModel? data) {
    if (data == null) return Container();
    String status = data.status;

    ///我是不是这个回流单的中拍买家
    bool isMineTender = false;
    if (data.winning_order != null) {
      isMineTender = (data.winning_order?["user_id"] ?? 0) ==
          UserUtil.getUserId(Get.context!);
    }

    String? _tenderPrice = data.tenderPrice;

    Widget _buildButtonText() {
      Function openDialog = () {
        RouteUtil.checkLogin(context, () {
          Function callback = () {
            bool result = model.isBidder;
            //判断是否有保证金
            if (!model.isWhite) {
              if (!result) {
                result = false;
                DialogUtil.showMyDialog(
                    dialogType: DialogType.toPayBond,
                    leftButtonOnTap: () {},
                    rightButtonOnTap: () {});
              } else {
                result = true;
              }
            } else {
              result = true;
            }
            if (result) {
              //弹出框
              TenderFormDialogUtil.show(
                widget.id,
                () {
                  initCommentData();
                  initProductData();
                },
                data.originalData,
                previous_max_tender_price: data.previous_max_tender_price,
                price_range: data.priceRange,
              );
            }
          };
        });
      };

      if (_tenderPrice == null) {
        return Container(
          height: 40.w,
          child: Consumer<UserProvider>(
            builder: (ctx, model, child) {
              return ButtonWidget(
                child: Text(
                  "出个价",
                  style: TextStyle(
                      fontSize: 14.sp,
                      color: Colors.white,
                      fontWeight: FontWeight.w500),
                ),
                type: ButtonType.bgOrange,
                onPressed: () {
                  openDialog();
                },
                enabled: true,
              );
            },
          ),
        );
      } else if (data.status == "evaluation") {
        return ButtonWidget(
          height: 40.0,
          enabled: true,
          type: ButtonType.bgOrange,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(
                "我要加价",
                style: TextStyle(
                    fontSize: 14.sp,
                    color: Colors.white,
                    fontWeight: FontWeight.w500),
              ),
              Text(
                "当前出价¥${getMoneyStyleStr(((double.tryParse(_tenderPrice) ?? 0).toInt()).toString())}",
                style: TextStyle(
                  fontSize: 12.sp,
                  color: Colors.white,
                ),
              ),
            ],
          ),
          onPressed: () {
            StatisticsUtil.event(SystemEvent.jia_jia_dian_ji, {
              "backflow_id": data.id.toString(),
            });
            openDialog();
          },
        );
      } else {
        return ButtonWidget(
          height: 40.0,
          enabled: false,
          type: ButtonType.bdGray,
          child: '我已出价￥$_tenderPrice',
        );
      }
    }

    List<Widget> _buildStarRowView = [];
    String _staredIcon = "";
    if (data.stared) {
      //已收藏
      _staredIcon = 'backflows/love';
    } else {
      _staredIcon = 'backflows/un_love';
    }
    _buildStarRowView = [
      Container(
        child: buildIcon(_staredIcon,
            (data.originalData['backflow_star_count'] ?? 0).toString(),
            () async {
          RouteUtil.checkLogin(context, () async {
            BidderGoodsDetailHandler.starBackflow(data.stared, widget.id, () {
              initProductData();
            });
          });
        }),
        alignment: Alignment.center,
        width: 40.w,
      ),
      SizedBox(
        width: 20.w,
      ),
      buildIcon("user/service", "客服", () {}),
    ];

    Widget containerWrap(Widget child) {
      return Container(
        height: buttom_height,
        padding: EdgeInsets.only(
          left: 15.w,
          right: 12.w,
          bottom: 7.5.w,
        ),
        decoration: BoxDecoration(
          color: Colors.white,
          boxShadow: [
            BoxShadow(
              offset: Offset(0, -1),
              color: Color(0x1A000000).withOpacity(0.05),
              blurRadius: 2.w,
            ),
          ],
        ),
        alignment: Alignment.centerLeft,
        child: child,
      );
    }

    Widget buildMineStaredWidget() {
      return Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          RoucesUtil.getAssetsIcon("backflows/un_love", 19.w),
          SizedBox(
            width: 3.w,
          ),
          Text(
            "${getStaredStr(data.originalData['backflow_star_count'] ?? 0)}关注",
            style: TextStyle(color: Color(0xFF333333), fontSize: 10.sp),
          ),
          SizedBox(
            width: 20.w,
          ),
        ],
      );
    }

    Map<String, Widget? Function(BackflowModel)> _buildMapWidget = {
      "evaluation": (BackflowModel _data) {
        Widget? _tempWidget;
        if (!isMine) {
          _tempWidget = containerWrap(
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                ..._buildStarRowView,
                SizedBox(
                  width: 20.w,
                ),
                Expanded(
                  flex: 1,
                  child: _buildButtonText(),
                ),
              ],
            ),
          );
        } else if (isMine && data.tendersCount > 0) {
          _tempWidget = containerWrap(
            Row(
              children: [
                buildMineStaredWidget(),
                SizedBox(
                  width: 14.w,
                ),
                Expanded(
                  child: Container(
                    height: 40.w,
                    decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(50),
                        border: Border.all(
                          width: 1,
                          color: ColorConf.normal,
                        )),
                    child: Center(
                        child: GestureDetector(
                      child: Container(
                        child: Text(
                          "提前结拍",
                          style: TextStyle(
                            fontSize: 16.sp,
                            color: ColorConf.normal,
                          ),
                        ),
                      ),
                      onTap: () {
                        if (data.tendersCount == 0) {
                          ToastUtil.show("当前没有人出价，无法结拍");
                        } else {}
                      },
                    )),
                  ),
                ),
              ],
            ),
          );
        } else if (isMine) {
          _tempWidget = containerWrap(
            buildMineStaredWidget(),
          );
        }
        return _tempWidget;
      },
      //根据前段判断来生成，非后端字段
      "wait_pay": (BackflowModel _data) {
        Widget? _tempWidget;
        if (isMineTender) {
          _tempWidget = containerWrap(
            ButtonWidget(
              child: Text(
                "立即付款",
                style: TextStyle(
                  fontSize: 14.sp,
                  color: Colors.white,
                  fontWeight: FontWeight.w500,
                ),
              ),
              type: ButtonType.bgOrange,
              onPressed: () {
                int orderId = widget.orderId;
                if (orderId == -1) {
                  orderId = data.winning_order?['id'] ?? -1;
                }
              },
              enabled: true,
            ),
          );
        }
        if (isMine) {
          _tempWidget = containerWrap(
            buildMineStaredWidget(),
          );
        }
        return _tempWidget;
      },
      //待确认
      "waitconfirm": (BackflowModel _data) {
        Widget? _tempWidget;
        if (isMine) {
          List<Widget> list = [];
          Widget cancel = ButtonWidget(
            height: 40.0,
            enabled: true,
            width: 88,
            type: ButtonType.bdGray,
            child: '拒绝',
            onPressed: () {},
          );
          Widget returnMoney = Expanded(
            child: Container(
              child: ButtonWidget(
                enabled: true,
                type: ButtonType.bgOrange,
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Text(
                      '接受回款',
                      style: TextStyle(
                        color: ColorConf.white,
                        fontSize: 14.sp,
                      ),
                    ),
                    Text(
                      '赚￥${data.immediate_discount_price ?? "0"}',
                      style: TextStyle(
                        color: ColorConf.white,
                        fontSize: 12.sp,
                      ),
                    ),
                  ],
                ),
                height: 40.0,
                onPressed: () {},
              ),
              margin: EdgeInsets.only(left: 10.w),
            ),
          );
          list.add(buildMineStaredWidget());
          list.add(cancel);
          list.add(returnMoney);

          _tempWidget = containerWrap(Container(
            child: Row(
              children: list,
            ),
            width: Get.width,
          ));
        } else if (!['', null].contains(data.tenderPrice)) {
          //tender_price字段是指我对该回流单的出价,卖家不能出价，所以卖家这个字段为null
          return containerWrap(
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                ..._buildStarRowView,
                SizedBox(
                  width: 20.w,
                ),
                Expanded(
                  flex: 1,
                  child: _buildButtonText(),
                ),
              ],
            ),
          );
        }
        return _tempWidget;
      },
      "back": (BackflowModel _data) {
        Widget? _tempWidget;
        if (data.canBack) {
          _tempWidget = Row(
            children: [
              Expanded(
                child: containerWrap(
                  ButtonWidget(
                    type: ButtonType.bdGrayWithTextBlack,
                    child: '收回货品',
                    height: 40.0,
                    onPressed: () async {
                      BidderGoodsDetailHandler.handlerTakeBack(data);
                    },
                  ),
                ),
              ),
              if (data.can_evaluated_again && data.isGoldBackflow == false)
                Expanded(
                  child: containerWrap(ButtonWidget(
                    enabled: true,
                    type: ButtonType.bdYellow,
                    child: '重新${App.evaluation_text}',
                    height: 40.0,
                    onPressed: () {},
                  )),
                ),
            ],
          );
        } else {
          _tempWidget = Container();
        }
        return _tempWidget;
      },
      "finished": (BackflowModel _data) {
        return Container();
      },
      "closed": (BackflowModel _data) {
        return Container();
      },
    };
    Widget? Function(BackflowModel)? resultWidget = _buildMapWidget[status];

    if (resultWidget != null && resultWidget(data) != null) {
      return resultWidget(data)!;
    } else {
      return Container(
        width: Get.width,
        height: 52.w,
        decoration: BoxDecoration(
          color: rgba(255, 255, 255, 1),
          border: Border(
            top: BorderSide(
              width: 1,
              color: rgba(0, 0, 0, 0.10),
            ),
          ),
        ),
        child: Row(
          children: [
            Expanded(
              child: Container(
                child: GestureDetector(
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      RoucesUtil.getAssetsIcon(_staredIcon, 19.w),
                      SizedBox(
                        width: 5.w,
                      ),
                      Text(
                        '${getStaredStr(data.originalData['backflow_star_count'] ?? 0)}',
                        style: TextStyle(
                            color: Color(0xFF333333), fontSize: 10.sp),
                      )
                    ],
                  ),
                  onTap: () {
                    RouteUtil.checkLogin(context, () async {
                      BidderGoodsDetailHandler.starBackflow(
                          data.stared, widget.id, () {
                        data.stared = !data.stared;
                        if (mounted) setState(() {});
                        initProductData();
                      });
                    });
                  },
                ),
                alignment: Alignment.center,
              ),
            ),
            Container(
              width: 1.w,
              color: rgba(238, 238, 238, 1),
              height: 52.w,
            ),
            Expanded(
              child: buildServiceWidget(),
            ),
          ],
        ),
      );
    }
  }

  String getPercentageStr(double num) {
    String rateStr = "90%-100%";

    double rate_of_bargain = num;
    int minRateDouble = (rate_of_bargain * 10).floor();

    int maxRateDouble = (rate_of_bargain * 10).ceil();

    if (rate_of_bargain == 0) {
      rateStr = "0-10%";
    } else {
      if (minRateDouble == maxRateDouble) {
        minRateDouble -= 1;
      }
      rateStr =
          "$minRateDouble${minRateDouble <= 0 ? "" : "0"}%-${maxRateDouble}0%";
    }

    return rateStr;
  }

  Widget render() {
    String? _status = data?.status;
    String? _strategy = data?.strategy;
    String? _title = data?.title;
    int _tendersCount = data?.tendersCount ?? 0;
    String _tenderPrice = data?.tenderPrice ?? "0";
    int _limited = data?.limited ?? 0;
    bool showVideo = (['waitconfirm', 'wait_pay', 'finished', 'closed', 'back']
            .contains(_status)) &&
        (data?.recording_video.isNotEmpty ?? false);

    String turnoverRateStr = getPercentageStr(
        double.tryParse(data?.user['rate_of_bargain'] ?? '0') ?? 0);
    String priceRateStr = getPercentageStr(
        double.tryParse(data?.user['price_rate_of_bargain'] ?? '0') ?? 0);

    return _TenderContent(
      top: [
        _TenderBanner(
          left: renderTenderBannerLeft(data),
          right: renderTenderBannerRight(data),
        ),
        Container(
          width: Get.width,
          height: 60.w,
          margin: EdgeInsets.only(bottom: 12.w),
          decoration: BoxDecoration(
            color: Color(0xFFF6F6F6),
            borderRadius: BorderRadius.circular(16.w),
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Expanded(
                flex: 10,
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Builder(builder: (ctx) {
                      int normal_level = data?.user['normal_level'] ?? 0;
                      String normal_level_str = normal_level.toString();
                      if (normal_level >= 5) {
                        normal_level_str = '5+';
                      }

                      return Image.asset(
                        'images/lt_user/owner/level_$normal_level_str.png',
                        width: 26.w,
                        height: 14.w,
                        fit: BoxFit.cover,
                      );
                    }),
                    VEmptyView(5.w),
                    Text(
                      "卖家等级",
                      style: TextStyle(
                        fontSize: 12.sp,
                        color: UIConstant.color66,
                      ),
                    ),
                  ],
                ),
              ),
              Expanded(
                child: Center(
                  child: Container(
                    alignment: Alignment.center,
                    width: 1.w,
                    height: 21.w,
                    color: Color(0xFFE9E9E9),
                  ),
                ),
                flex: 1,
              ),
              Expanded(
                flex: 10,
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(
                      "$turnoverRateStr",
                      style: TextStyle(
                        fontSize: 12.sp,
                        fontWeight: FontWeight.w500,
                        color: UIConstant.color33,
                      ),
                    ),
                    VEmptyView(5.w),
                    GestureDetector(
                      behavior: HitTestBehavior.opaque,
                      onTap: () {
                        DialogUtil.showMyDialog(
                            dialogType: DialogType
                                .bidder_detail_turnover_rate_description);
                      },
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Text(
                            "数量成交率",
                            style: TextStyle(
                              fontSize: 12.sp,
                              color: UIConstant.color66,
                            ),
                          ),
                          HEmptyView(2.w),
                          Image.asset(
                            'images/ic_order_doubt_lt.png',
                            width: 12.w,
                            height: 12.w,
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
              Expanded(
                child: Center(
                  child: Container(
                    alignment: Alignment.center,
                    width: 1.w,
                    height: 21.w,
                    color: Color(0xFFE9E9E9),
                  ),
                ),
                flex: 1,
              ),
              Expanded(
                flex: 10,
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(
                      "$priceRateStr",
                      style: TextStyle(
                        fontSize: 12.sp,
                        fontWeight: FontWeight.w500,
                        color: UIConstant.color33,
                      ),
                    ),
                    VEmptyView(5.w),
                    GestureDetector(
                      behavior: HitTestBehavior.opaque,
                      onTap: () {
                        DialogUtil.showMyDialog(
                            dialogType: DialogType
                                .bidder_detail_price_rate_description);
                      },
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Text(
                            "金额成交率",
                            style: TextStyle(
                              fontSize: 12.sp,
                              color: UIConstant.color66,
                            ),
                          ),
                          HEmptyView(2.w),
                          Image.asset(
                            'images/ic_order_doubt_lt.png',
                            width: 12.w,
                            height: 12.w,
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
        CopyTextWidget(
          title: _title ?? "",
        ),
        if (((data?.originalData['my_tender_history'] ?? {}) as Map).isNotEmpty)
          GestureDetector(
            child: Container(
              margin: EdgeInsets.only(
                top: 10.w,
              ),
              height: 30.w,
              width: Get.width,
              decoration: BoxDecoration(
                color: rgba(255, 143, 0, 0.08),
                borderRadius: BorderRadius.circular(4.w),
              ),
              padding: EdgeInsets.only(
                left: 10.w,
                right: 10.w,
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Row(
                    children: [
                      RoucesUtil.getAssetsIcon('ic_bidder_detail_pai_guo_lt', 13),
                      SizedBox(
                        width: 6.w,
                      ),
                      buildW500Text("我拍过"),
                    ],
                  ),
                  Row(
                    children: [
                      buildGreyText('上次出价'),
                      SizedBox(
                        width: 4.w,
                      ),
                      buildW500Text(
                          "¥${(data?.originalData['my_tender_history']?['price'] ?? "0").toString()}"),
                      SizedBox(
                        width: 10.w,
                      ),
                      buildGreyText("|"),
                      SizedBox(
                        width: 10.w,
                      ),
                      buildGreyText("上次中拍价"),
                      SizedBox(
                        width: 4.w,
                      ),
                      buildW500Text(
                          "¥${double.parse((data?.originalData['my_tender_history']?['previous_backflow_price'] ?? "0").toString())}"),
                      SizedBox(
                        width: 10.w,
                      ),
                      Image(
                        image: AssetImage('images/lt_common/right_arrow.png'),
                        width: 6.w,
                      ),
                    ],
                  ),
                ],
              ),
            ),
            onTap: () {},
          ),
        _DetailInfoWidget(
          data: data,
        ),
        if (showVideo)
          GestureDetector(
            child: Container(
              height: 42.w,
              width: Get.width,
              decoration: BoxDecoration(
                color: Color(0xFFFBF6EB),
                borderRadius: BorderRadius.circular(8.w),
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Image.asset(
                    'images/ic_bidder_detail_play_lt.png',
                    width: 20.w,
                    height: 20.w,
                    color: Color(0xFFFF8F00),
                  ),
                  Container(
                    margin: EdgeInsets.only(left: 6.w),
                    child: Text(
                      '货品讲解录播视频',
                      style: TextStyle(
                        fontSize: 14.sp,
                        color: Color(0xFFFF8F00),
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                  ),
                ],
              ),
              margin: EdgeInsets.only(bottom: 15.w),
            ),
            behavior: HitTestBehavior.opaque,
            onTap: () {
              bool result = (data?.studios?.length ?? 0) > 0 &&
                  (data?.studios?[0]?['switch'] ?? false);
              LiveRecordForm live = LiveRecordForm.DetailNoLiving;
              if (result) {
                List<ChannelModel> channelList = (data?.studios)
                        ?.map((item) => new ChannelModel.fromJson(item))
                        .toList() ??
                    [];
                StreamConf.liveId = channelList[0].id;
                StreamConf.channelKey = channelList[0].key;
                StreamConf.channelModel = channelList[0];
                //需要去看直播
                live = LiveRecordForm.DetailToLiving;
              }
              Map<String, dynamic>? map = data?.toJson(data!);
              LiveRecordingDialogUtil.showDialog(
                data?.recording_video ?? "",
                StreamConf.liveId,
                map,
                liveRecordForm: live,
              );
            },
          )
      ],
      bottom: [
        CommentListWidget(
          status: _status ?? "",
          strategy: _strategy ?? "",
          tenderPrice: _tenderPrice,
          rateForDeducting: data?.rateForDeducting ?? "0",
          comments: comments,
          backflowModel: data,
          body: body,
          title: title,
          remaining: _limited - _tendersCount,
          isEvaluated: !['', null].contains(_tenderPrice),
          isMine: isMine,
        ),
      ],
    );
  }

  buildGreyText(String text) {
    return Text(
      text,
      style: TextStyle(
        fontSize: 12.sp,
        color: rgba(153, 153, 153, 1),
      ),
    );
  }

  buildW500Text(String text) {
    return Text(
      text,
      style: TextStyle(
        fontSize: 12.sp,
        color: rgba(51, 51, 51, 1),
        fontWeight: FontWeight.w500,
      ),
    );
  }

  String? _getStatus(status) {
    if (evaluationStatusList.contains(status)) {
      return 'evaluation';
    } else if (onsaleStatusList.contains(status)) {
      return 'onsale';
    }
    return "";
  }

  buildIcon(String icon, String text, GestureTapCallback onTap,
      {bool showCount: false, int count: 0}) {
    double size = 12;
    double offsetX = -2;
    double offsetY = 3;
    String countStr = "";
    if (showCount) {
      int length = count.toString().length;
      size += 3 * (length - 1); //数字圈的大小
      if (length >= 2) {
        offsetX = -3; //偏移 右上角
        offsetY = 3; //偏移 右上角
      }
      countStr = count.toString();
      if (count >= 99) {
        countStr = "99+";
        size = 20;
        offsetX = -7; //偏移 右上角
        offsetY = 0; //偏移 右上角
      }
    }
    return InkWell(
      child: Stack(
        children: [
          Container(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                RoucesUtil.getAssetsIcon(icon, 19.w),
                SizedBox(
                  height: 3.w,
                ),
                Text(
                  text,
                  style: TextStyle(color: Color(0xFF333333), fontSize: 10.sp),
                )
              ],
            ),
          ),
          Positioned(
            right: offsetX,
            top: offsetY,
            child: showCount
                ? Container(
                    alignment: Alignment.center,
                    width: size,
                    height: size,
                    child: Text(
                      countStr.toString(),
                      style:
                          TextStyle(fontSize: 9.sp, color: Color(0xFFE02020)),
                    ),
                    decoration: BoxDecoration(
                        border:
                            Border.all(width: 1.w, color: Color(0xFFE02020)),
                        borderRadius: BorderRadius.circular(50.w)),
                  )
                : Container(),
          )
        ],
        clipBehavior: Clip.none,
      ),
      onTap: onTap,
    );
  }
}

//我的评价
class MyComment extends StatelessWidget {
  late BackflowModel? data = null;

  MyComment({
    Key? key,
    this.data,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    String comment = data?.rating?['comment'] ?? "";
    int rank = data?.rating?['rank'] ?? 0;
    bool showDefault = false;
    if (comment.isEmpty) {
      comment = "用户未写评语";
      showDefault = true;
    }
    return Visibility(
      child: Container(
        color: ColorConf.white,
        padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 12.w),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            SizedBox(
              height: 8.w,
            ),
            Align(
              child: Text(
                '我的评价',
                style: TextStyle(
                  fontSize: 16.sp,
                  fontWeight: FontWeight.bold,
                  color: ColorConf.normal,
                ),
              ),
              alignment: Alignment.centerLeft,
            ),
            SizedBox(
              height: 18.sp,
            ),
            Container(
              child: Row(
                children: [
                  Text(
                    '总体评价',
                    style: TextStyle(fontSize: 14.sp, color: Color(0xFF333333)),
                  ),
                  SizedBox(
                    width: 20.w,
                  ),
                  ...List.generate(
                      rank,
                      (index) => Padding(
                            padding: EdgeInsets.only(right: 10.w),
                            child: RoucesUtil.getAssetsIcon(
                                'backflows/star', 16.w),
                          ))
                ],
              ),
              margin: EdgeInsets.only(bottom: 10.w),
            ),
            Container(
              child: Row(
                children: [
                  Text(
                    '$comment',
                    style: TextStyle(
                        fontSize: 14.sp,
                        color: showDefault
                            ? Color(0xFF999999)
                            : Color(0xFF333333) //FF999999
                        ),
                  )
                ],
              ),
              margin: EdgeInsets.only(bottom: 10.w),
            ),
            Container(
              height: 10.w,
              color: Color(0xFFF5F5F5),
              width: double.infinity,
            ),
          ],
        ),
      ),
      visible: (data?.isMine(UserUtil.getUserId(context)) ?? false) &&
          !(data?.isRating ?? false),
    );
  }
}

//${App.evaluation_text}说明
class BidDescription extends StatelessWidget {
  BidDescription({Key? key}) : super(key: key);

  List desc = [
    '，出价额度为支付保证金的${ConfigProviderUtil.available_bid_multiple}倍（当保证金余额大于等于¥${ConfigProviderUtil.max_deductible_amount}时，出价不限额度）',
    '出价提交后只可加价，中拍后未按时支付中拍款将扣除相当于中拍款${ConfigProviderUtil.deduct_guarantee_rate_str}的保证金，支付中拍款后不可退货，请确保自己拥有足够的鉴定、鉴别商品的能力',
    '付款后的中拍订单可选择取回货品或委托平台寄售'
  ];

  final double leading = 0.8;
  final double textLineHeight = 0.8;

  /// 文本间距
  final double fontSize = 14;

  @override
  Widget build(BuildContext context) {
    return Container(
      color: ColorConf.white,
      padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 12.w),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(
            height: 8.w,
          ),
          Align(
            child: Text(
              '${App.evaluation_text}说明',
              style: TextStyle(
                fontSize: 16.sp,
                fontWeight: FontWeight.bold,
                color: ColorConf.normal,
              ),
            ),
            alignment: Alignment.centerLeft,
          ),
          SizedBox(
            height: 20.w,
          ),
          Container(
            height: 71.w,
            width: double.infinity,
            child: Image.asset(
              RoucesUtil.getAssets('backflows/bid_desc'),
            ),
            padding: EdgeInsets.symmetric(horizontal: 20.w),
          ),
          SizedBox(
            height: 18.w,
          ),
          Container(
            padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 18.w),
            decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(8.w),
                color: Color(0xFFA38B78).withOpacity(0.06)),
            child: Column(
              children: [
                ...List.generate(
                  desc.length,
                  (index) {
                    return Container(
                      child: Text.rich(
                        TextSpan(
                          style: TextStyle(
                            fontSize: 14.sp,
                            color: Color(0xFF666666),
                            fontWeight: FontWeight.w400,
                          ),
                          children: [
                            icon(),
                            if (index == 0)
                              TextSpan(
                                text: '首次出价，点击“出个价”按钮支付保证金即可参与出价',
                                style: TextStyle(
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                            TextSpan(
                              text: desc[index],
                              style: TextStyle(
                                height: 2,
                              ),
                            )
                          ],
                        ),
                      ),
                    );
                  },
                ),
                SizedBox(
                  height: 10.w,
                ),
                InkWell(
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Text(
                        '查看完整的买家须知',
                        style: TextStyle(
                          fontSize: 12.sp,
                          color: Color(0xFF999999),
                        ),
                      ),
                      SizedBox(
                        width: 4.w,
                      ),
                      Image.asset(
                        'images/lt_common/right_arrow.png',
                        width: 5.w,
                        height: 9.w,
                      )
                    ],
                  ),
                  onTap: () {},
                )
              ],
            ),
          )
        ],
      ),
      margin: EdgeInsets.only(
        bottom: UserUtil.isLogin(context)
            ? 0
            : 52.w + ScreenUtil().bottomBarHeight + 40.w,
      ),
    );
  }

  WidgetSpan icon() {
    return WidgetSpan(
      alignment: PlaceholderAlignment.middle,
      child: Container(
        alignment: Alignment.center,
        width: 4.w,
        height: 4.w,
        decoration: BoxDecoration(
            color: UIConstant.color99,
            borderRadius: BorderRadius.circular(50.w)),
        margin: EdgeInsets.only(right: 8.w),
      ),
    );
  }

  text(String str) {
    return Text(
      str,
      style: TextStyle(fontSize: 12.sp, color: Color(0xFF666666)),
    );
  }
}

class _TenderContent extends StatelessWidget {
  List<Widget> top;
  List<Widget> bottom;

  _TenderContent({
    Key? key,
    required this.top,
    required this.bottom,
  }) : super(key: key);

  Widget _padding(children) {
    return Padding(
      padding: GetPadding.only(left: 12.w, right: 12.w),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: children,
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Transform.translate(
      offset: Offset(0, -13.w),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _padding(top),
          Container(
            height: 10.w,
            color: Color(0xFFF5F5F5),
          ),
          _padding(bottom),
        ],
      ),
    );
  }
}

class _TenderBanner extends StatelessWidget {
  Widget? left;
  Widget? right;

  _TenderBanner({
    Key? key,
    this.left,
    this.right,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: GetPadding.only(bottom: 20.w),
      decoration: BoxDecoration(
        borderRadius: GetRadius.all(8.w),
        boxShadow: [
          BoxShadow(
            color: ColorConf.yellow.withOpacity(0.4),
            offset: Offset(0, 10.w),
            blurRadius: 10.w,
          )
        ],
        color: ColorConf.white,
      ),
      clipBehavior: Clip.hardEdge,
      height: 68.w,
      child: Row(
        children: [
          Expanded(
            child: ClipPath(
              clipper: GetClipper(
                path: (Size size) {
                  double width = size.width;
                  double height = size.height;
                  return [
                    [0.0, 0.0],
                    [width, 0.0],
                    [width - 20, height / 2],
                    [width, height],
                    [0.0, height],
                    [0.0, 0.0],
                  ];
                },
              ),
              child: Container(
                height: 68.w,
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    colors: [
                      Color(0xFFFF7F00),
                      Color(0xFFFEBA07),
                    ],
                  ),
                ),
                child: this.left,
              ),
            ),
          ),
          Container(
            width: 130.w,
            child: this.right,
          )
        ],
      ),
    );
  }
}

class _DetailInfoWidget extends StatefulWidget {
  final BackflowModel? data;

  _DetailInfoWidget({
    Key? key,
    required this.data,
  }) : super(key: key);

  @override
  State<_DetailInfoWidget> createState() => _DetailInfoWidgetState();
}

class _DetailInfoWidgetState extends State<_DetailInfoWidget> {
  late List<Map<String, dynamic>> renderMap = [
    {
      'label': '相关证书:',
      'value': widget.data?.certificate ?? "",
      'format': (val) => val,
    },
    {
      'label': '瑕疵说明:',
      'value': widget.data?.flaw ?? "",
      'format': (val) => val,
    },
    {
      'label': '看货直播间:',
      'value': widget.data?.studios ?? [],
      'format': (val) => val,
    },
    {
      'label': '其他说明:',
      'value':
          "${widget.data?.tender_page_description ?? ""} ${widget.data?.description ?? ""}",
      'format': (val) => val,
    }
  ];

  List<Widget> renderList(
      evaluation_default_description_text, common_default_description_text) {
    List fileds = widget.data?.originalData['dynamic_fields'] ?? [];
    if (fileds.length == 0) return [Container()];
    String key = fileds[0] ?? "";
    String value = widget.data?.goods[key] ?? "";
    int index =
        renderMap.indexWhere((element) => (element['key'] ?? "") == key);
    String label = "尺寸大小:";
    if (index == -1) {
      renderMap.insert(renderMap.length - 1, {
        'label': label,
        'value': value,
        "key": key,
        'format': (val) => val,
      });
    }
    List<Widget> tempWidgetList = renderMap.map((item) {
      return renderItem(item, evaluation_default_description_text,
          common_default_description_text);
    }).toList();

    return tempWidgetList;
  }

  Widget renderItem(Map<String, dynamic> item,
      evaluation_default_description_text, common_default_description_text) {
    String label = item['label'];
    var value = item['format'](item['value'] ?? "");

    if (label == "看货直播间:") {
      if (value.length > 0) {
        value = ChannelModel.fromJson(value[0]).name +
            " " +
            ChannelModel.fromJson(value[0]).description;
      } else {
        value = "";
        return Container();
      }
    } else {
      if (value.isEmpty) {
        return Container();
      }
    }
    return Container(
      padding: GetPadding.only(bottom: 6.w),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            width: 80.w,
            child: Text(
              item['label'],
              style: TextStyle(
                color: ColorConf.lightGray,
                fontSize: 14.sp,
              ),
              softWrap: true,
            ),
          ),
          Expanded(
            child: Text(
              value,
              style: TextStyle(
                fontSize: 14.sp,
                color: ColorConf.normal,
              ),
            ),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<ConfigProvider>(
      builder: (BuildContext context, ConfigProvider value, Widget? child) {
        Map map = value.get('settings');
        String evaluation_default_description_text =
            map['evaluation_default_description_text'] ?? "";
        String common_default_description_text =
            map['common_default_description_text'] ?? "";
        return Padding(
          padding: GetPadding.only(top: 12.w, bottom: 14.w),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: renderList(evaluation_default_description_text,
                common_default_description_text),
          ),
        );
      },
    );
  }
}
